package com.hmall.cart.listener;

import com.hmall.cart.constants.MQConstant;
import com.hmall.cart.service.ICartService;
import com.hmall.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Collection;

// 监听订单服务的购物车删除消息
@Slf4j
@Component
@RequiredArgsConstructor
public class CartMqListener {
    private final ICartService cartService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstant.CART_QUEUE),
            exchange = @Exchange(name = MQConstant.CART_EXCHANGE, delayed = "true"),
            key = MQConstant.CART_ROUTING_KEY
    ))
    public void listenerCartDeleteMessage(Collection<Long> itemIds, Message message) {
        Long userId = message.getMessageProperties().getHeader("user-info");
        UserContext.setUser(userId);
        log.info("监听用户ID：{}，删除购物车商品id：{}", userId,itemIds);
        cartService.removeByItemIds(itemIds);
    }
}
